package com.hkts.naturalgas.association.service.serviceimpl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.hkts.naturalgas.association.entity.HktsRequestAddressAssociation;
import com.hkts.naturalgas.association.mapper.HktsRequestAddressAssociationMapper;
import com.hkts.naturalgas.association.service.IHktsRequestAddressAssociationService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hkts.naturalgas.config.datahandler.EnviromentConstance;
import com.hkts.naturalgas.config.datahandler.LinkExceptionTransitionTime;
import com.hkts.naturalgas.dictionaries.entity.HktsEnvironmentProtectionDictionaries;
import com.hkts.naturalgas.dictionaries.entity.HktsEnvironmentProtectionItem;
import com.hkts.naturalgas.dictionaries.service.IHktsEnvironmentProtectionDictionariesService;
import com.hkts.naturalgas.dictionaries.service.IHktsEnvironmentProtectionItemService;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.apache.commons.lang.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import java.sql.*;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author yck
 * @since 2023-02-26
 */
@Log4j2
@Service
@Transactional
public class HktsRequestAddressAssociationServiceImpl extends ServiceImpl<HktsRequestAddressAssociationMapper, HktsRequestAddressAssociation> implements IHktsRequestAddressAssociationService {


    @Autowired
    private HktsRequestAddressAssociationMapper hktsRequestAddressAssociationMapper;

    @Autowired
    public IHktsEnvironmentProtectionDictionariesService iHktsEnvironmentProtectionDictionariesService;

    @Autowired
    public IHktsEnvironmentProtectionItemService iHktsEnvironmentProtectionItemService;

    @Override
    public IPage<HktsRequestAddressAssociation> selectPage(Page<HktsRequestAddressAssociation> page, HktsRequestAddressAssociation hktsRequestAddressAssociation) {
        QueryWrapper<HktsRequestAddressAssociation> query = Wrappers.query();
        QueryWrapper<HktsRequestAddressAssociation> entityWrapper = getEntityWrapper(query, hktsRequestAddressAssociation);
        return hktsRequestAddressAssociationMapper.selectPage(page, entityWrapper);
    }


    @Override
    public List<HktsRequestAddressAssociation> selectList(HktsRequestAddressAssociation hktsRequestAddressAssociation) {
        QueryWrapper<HktsRequestAddressAssociation> query = Wrappers.query();
        QueryWrapper<HktsRequestAddressAssociation> entityWrapper = getEntityWrapper(query, hktsRequestAddressAssociation);
        return hktsRequestAddressAssociationMapper.selectList(entityWrapper);
    }

    /**
     * 公共查询条件
     *
     * @param entityWrapper
     * @return
     */
    public QueryWrapper<HktsRequestAddressAssociation> getEntityWrapper(QueryWrapper<HktsRequestAddressAssociation> entityWrapper, HktsRequestAddressAssociation hktsRequestAddressAssociation) {
        //条件拼接

        return entityWrapper;
    }


    @Override
    public Map<String, Object> getAssociations() {

        HktsEnvironmentProtectionDictionaries hktsEnvironmentProtectionDictionariesServiceDbTable = iHktsEnvironmentProtectionDictionariesService.getDbTable();
        List<HktsEnvironmentProtectionItem> hktsEnvironmentProtectionItems = iHktsEnvironmentProtectionItemService.getDbTable();
        List<String> list = new ArrayList<>();
        List<String> listFiled = new ArrayList<>();
        for (int i = 0; i < hktsEnvironmentProtectionItems.size(); i++) {
            if (!hktsEnvironmentProtectionItems.get(i).getDataType().equals(EnviromentConstance.DATE_TIME)) {
                list.add(hktsEnvironmentProtectionItems.get(i).getFieldName());
                listFiled.add(hktsEnvironmentProtectionItems.get(i).getCorrespondingField());
            }
        }
        QueryWrapper<HktsRequestAddressAssociation> query = Wrappers.query();
        query.lambda().eq(HktsRequestAddressAssociation::getTableId, hktsEnvironmentProtectionDictionariesServiceDbTable.getId());

        HktsRequestAddressAssociation hktsRequestAddressAssociation = hktsRequestAddressAssociationMapper.selectOne(query);
        //判断链接的当前状态
        //如果正常就正常请求 返回链接失败则设置该链接暂时失效
        //如果链接是失败状态判断是否到期到期则重新连接，没有直接返回上级为空
        //如果当前为失败状态查询为正常后设置该链接为正常状态
        Map<String, Object> data = new HashMap<>();
        data = getData(hktsRequestAddressAssociation, hktsEnvironmentProtectionDictionariesServiceDbTable.getTableName(), list, listFiled);
        if (data.get("code").toString().equals("500")) {
            log.error(hktsEnvironmentProtectionDictionariesServiceDbTable.getTableDescribe() + "表连接异常");
            hktsRequestAddressAssociation.setInvalidTime(LocalDateTime.now());
            hktsRequestAddressAssociationMapper.updateById(hktsRequestAddressAssociation);
        }else {
            return data;
        }
        return data;
    }

    public static Map<String, Object> getData(HktsRequestAddressAssociation hktsRequestAddressAssociation, String dataName, List<String> field, List<String> listField) {
        String URL = "jdbc:mysql://" + hktsRequestAddressAssociation.getUrl() + "?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone = GMT";
        String USER = hktsRequestAddressAssociation.getUsername();
        String PASSWORD = hktsRequestAddressAssociation.getPassword();
        Connection conn = null;
        Statement st = null;
        Map<String, Object> resultMap = new HashMap<>();
        //1.加载驱动程序
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            //设置超时时间
            DriverManager.setLoginTimeout(1);
            //2.获得数据库链接
            conn = DriverManager.getConnection(URL, USER, PASSWORD);
            st = conn.createStatement();
            //3.通过数据库的连接操作数据库，实现增删改查（使用Statement类）
            String sql = "";
            if (dataName.equals("hk_ds_tuoliu")) {
                sql = "SELECT * from " + dataName + " order by datetime desc LIMIT 0,1 ";
            }
            ResultSet rs = st.executeQuery(sql);
            while (rs.next()) {
                for (int i = 0; i < field.size(); i++) {
                    String string = rs.getString(listField.get(i));
                    resultMap.put(field.get(i), string);
                }
            }
            resultMap.put("code", "200");
            rs.close();
        } catch (Exception e) {
            log.error(e.getMessage());

            resultMap.put("code", "500");
            //e.printStackTrace();
        } finally {
            try {
                if (st != null) {
                    st.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
            try {
                if (conn != null) {
                    conn.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        //4.处理数据库的返回结果(使用ResultSet类)
        //关闭资源
        return resultMap;
    }
}
